package cn.edu.dgut.experiment2.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@EnableConfigurationProperties(CustomProperties.class)
public class Lab2AutoConfig {

    @Bean
    @ConditionalOnProperty(prefix = "experiment2.auto", name = "enable", havingValue = "true")
    public CustomCommandlineRunner customCommandlineRunner(Environment env) {
        return new CustomCommandlineRunner(env);
    }

    /**
     * 覆盖spring的bean，使用原来的properities，不想多写一个配置类了
     *
     * @param taskExecutionProperties
     * @return
     */
    @Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
    public ThreadPoolTaskExecutor customThreadPoolTaskExecutor(TaskExecutionProperties taskExecutionProperties) {
        TaskExecutionProperties.Pool pool = taskExecutionProperties.getPool();

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setThreadNamePrefix("myThread:");
        taskExecutor.setMaxPoolSize(pool.getMaxSize());
        taskExecutor.setCorePoolSize(pool.getCoreSize());
        taskExecutor.setKeepAliveSeconds(((Long) (pool.getKeepAlive().getSeconds())).intValue());
        taskExecutor.setQueueCapacity(pool.getQueueCapacity());
        return taskExecutor;
    }


}
